package com.sqx.modules.brand.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.Result;
import com.sqx.modules.brand.dao.BrandDao;
import com.sqx.modules.brand.entity.Brand;
import com.sqx.modules.brand.service.BrandService;
import com.sqx.modules.goods.dao.GoodsDao;
import com.sqx.modules.goods.entity.Goods;
import com.sqx.modules.goodsType.dao.GoodsTypeDao;
import com.sqx.modules.goodsType.entity.GoodsType;
import com.sqx.modules.goodsType.service.GoodsTypeService;
import com.sqx.modules.labelType.dao.LabelTypeDao;
import com.sqx.modules.labelType.entity.LabelType;
import com.sqx.modules.recovery.dao.GoodsRecoveryDao;
import com.sqx.modules.recovery.dao.GoodsSpecificationsDao;
import com.sqx.modules.recovery.entity.GoodsRecovery;
import com.sqx.modules.recovery.entity.GoodsSpecifications;
import com.sqx.modules.search.service.SearchRecordService;
import com.sqx.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Admin
 * @description 针对表【brand_type(品牌分类表)】的数据库操作Service实现
 * @createDate 2024-09-14 14:35:38
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandDao, Brand>
        implements BrandService {

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private SearchRecordService searchRecordService;

    @Autowired
    private LabelTypeDao labelTypeDao;

    @Autowired
    private GoodsTypeService goodsTypeService;

    @Autowired
    private GoodsTypeDao goodsTypeDao;

    @Autowired
    private GoodsSpecificationsDao goodsSpecificationsDao;

    @Autowired
    private GoodsRecoveryDao goodsRecoveryDao;

    @Override
    public Result addBrand(Brand brand) {
        SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        if (user == null) {
            return Result.error("用户未登录");
        }
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("brand_name", brand.getBrandName());
        if (brand.getId() != null) {
            brand.setCreateTime(new Date());
            brand.setLabelId(brand.getLabelId());
            baseMapper.updateById(brand);
            return Result.success();
        } else {
            brand.setLabelId(brand.getLabelId());
            brand.setCreateTime(new Date());
            baseMapper.insert(brand);
            return Result.success();
        }
    }

    @Override
    public Result deleteBrand(Long id) {
        SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        if (user == null) {
            return Result.error("用户未登录");
        }
        Brand brand = baseMapper.selectById(id);
        Goods goods = goodsDao.selectOne(new QueryWrapper<Goods>().eq("brand_id", brand.getId()));
        if (goods != null) {
            return Result.error("该品牌下有商品，无法删除");
        }
        if (brand != null) {
            baseMapper.deleteById(id);
            return Result.success();
        }
        return Result.error("该品牌不存在或已删除");
    }

    @Override
    public IPage<Brand> getBrandList(Integer page, Integer limit, Brand brand) {
        Page<Brand> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        if (brand.getIsHot() != null && brand.getIsHot() == 1) {
            return baseMapper.selectListByHot(pages, brand);
        } else {
            return baseMapper.selectListByPage(pages, brand);
        }
    }

    @Override
    public Result selectById(Long id) {
        SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        if (user == null) {
            return Result.error("用户未登录");
        }
        Brand brand = baseMapper.selectById(id);
        if (brand == null) {
            return Result.error("该品牌类型不存在");
        }
        return Result.success().put("data", brand);
    }

    @Override
    public Result selectByTypeId(Long labelId, Integer isHot) {
        if (labelId == null) {
            return Result.error("参数错误");
        }
        if (baseMapper.selectCount(new QueryWrapper<Brand>().eq("label_id", labelId)) == 0) {
            return Result.success().put("data", Collections.emptyList());
        }
        return Result.success().put("data", baseMapper.selectList(new QueryWrapper<Brand>()
                .eq("label_id", labelId)
                .eq(isHot != null, "is_hot", 1)
                .orderByDesc("create_time")));
    }

    @Override
    public Result selectByTypeIds(Long labelId, Integer isHot, Integer isRecovery) {
//        if (baseMapper.selectCount(new QueryWrapper<Brand>().eq("label_id", labelId)) == 0) {
//            return Result.success().put("data", Collections.emptyList());
//        }
        return Result.success().put("data", baseMapper.selectListByIsRecovery(labelId, isRecovery, isHot));
    }

    @Override
    public Result selectByTypeIdByBrandName(Long labelId, Integer isHot, Integer isRecovery, String brandName, Long userId) {
        if (StringUtils.isNotBlank(brandName) && !" ".equals(brandName)) {
            searchRecordService.saveRecordInfo(brandName, userId);
            List<Brand> brands = baseMapper.selectListByIsRecoveryName(labelId, isRecovery, isHot, brandName);
            if (brands.isEmpty()) {
                List<LabelType> labelTypes = labelTypeDao.selectList(new QueryWrapper<LabelType>()
                        .eq("label", brandName)
                        .eq("is_enable", 1)
                        .eq("is_type", 0)
                        .eq("is_recovery", 1));
                if (labelTypes != null && !labelTypes.isEmpty()) {
//                    List<GoodsType> result = new ArrayList<>();
//                    List<GoodsType> goodsTypes = goodsTypeDao.selectList(new QueryWrapper<GoodsType>().eq("type_id",labelTypes.get(0).getLabelId()));
//                    for (GoodsType allGoodsType : goodsTypes) {
//                        if (allGoodsType.getParentId() == 0) {
//                            if (allGoodsType.getTypeName().contains("手机")) {
//                                List<Brand> brands1 = getBrandsByLabelId(allGoodsType.getLabelId());
//                                allGoodsType.setBrands(brands1);
//                                allGoodsType.setGoodsTypeList(null);
//                            } else {
//                                // 获取所有符合条件的商品类型的 label_id
//                                Long finalLabelId = goodsTypes.get(0).getLabelId();
//                                List<GoodsType> allGoodsTypeList = goodsTypeDao.selectList(new QueryWrapper<GoodsType>().eq("label_id", finalLabelId));
//                                allGoodsType.setGoodsTypeList(getChildrenLists(allGoodsType, allGoodsTypeList, result));
//                            }
//                        } else {
//                            if (allGoodsType.getParentId() != 0) {
//                                GoodsType parent = goodsTypeDao.selectById(allGoodsType.getParentId());
////                    allGoodsType.setGoodsTypeList(getChildrenList(allGoodsType, allGoodsTypes));
//                                parent.setGoodsTypeList(goodsTypes);
//                                return Result.success().put("data",Collections.singletonList(parent));
//                            }
//                        }
//                    }
                    List<Brand> brandList = baseMapper.selectListByIsRecovery(labelTypes.get(0).getLabelId(), 1, isHot);
                    return Result.success().put("data", brandList);
                } else if (labelTypes == null) {
                    return Result.success().put("data", Collections.emptyList());
                }
            }
            return Result.success().put("data", brands);
        }
        return Result.success().put("data", Collections.emptyList());
    }

    private List<GoodsType> getChildrenLists(GoodsType goodsType, List<GoodsType> all, List<GoodsType> result) {
        List<GoodsType> children = all.stream()
                .filter(categoryEntity -> categoryEntity.getParentId().equals(goodsType.getTypeId()))
                .sorted(Comparator.comparing(GoodsType::getSort))
                .peek(categoryEntity -> {
                    // 递归查找子节点
                    getChildrenLists(categoryEntity, all, result);
                })
                .collect(Collectors.toList());

        // 将子节点加入到结果列表中
        result.addAll(children);

        // 设置子节点列表
        goodsType.setGoodsTypeList(children);
        return result;
    }

    @Override
    public List<Brand> getBrandsByLabelId(Long labelId) {
        return baseMapper.selectList(new QueryWrapper<Brand>().eq("label_id", labelId));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result copyBrandListByRecycle(Long labelId, Long brandId) {
        LabelType labelType = labelTypeDao.selectById(labelId);
        Long labelId1;
        if (labelType != null) {
            LabelType labelType1 = labelTypeDao.selectLabelByIsRecovery(labelType.getLabel());
            if (labelType1 == null) {
                LabelType labelType2 = new LabelType();
                labelType2.setLabel(labelType.getLabel());
                labelType2.setIsEnable(1);
                labelType2.setIsRecovery(0);
                labelType2.setIsType(1);
                labelType2.setCreateTime(LocalDateTime.now());
                labelTypeDao.insert(labelType2);
                labelId1 = labelType2.getLabelId();
            } else {
                labelId1 = labelType1.getLabelId();
            }
            List<GoodsRecovery> goodsRecoveryList = goodsRecoveryDao.selectList(new QueryWrapper<GoodsRecovery>().eq("brand_id", brandId));
            if (goodsRecoveryList != null) {
                Brand brand1 = baseMapper.selectById(brandId);
                if (brand1 != null) {
                    Brand brand = new Brand();
                    brand.setLabelId(labelId1);
                    brand.setBrandName(brand1.getBrandName());
                    brand.setImg(brand1.getImg());
                    brand.setSort(brand1.getSort());
                    brand.setCreateTime(new Date());
                    brand.setState(brand1.getState());
                    brand.setClassify(brand1.getClassify());
                    brand.setIsHot(brand1.getIsHot());
                    baseMapper.insert(brand);
                    for (GoodsRecovery goodsRecovery : goodsRecoveryList) {
                        GoodsRecovery goodsRecovery1 = new GoodsRecovery();
                        goodsRecovery1.setName(goodsRecovery.getName());
                        goodsRecovery1.setBrandId(brand.getId());
                        goodsRecovery1.setCreateTime(new Date());
                        goodsRecovery1.setDeleteFlag(0);
//                            goodsRecovery1.setUpdateBy(userId);
                        goodsRecoveryDao.insert(goodsRecovery1);
                        List<GoodsSpecifications> list = goodsSpecificationsDao.selectList(new QueryWrapper<GoodsSpecifications>()
                                .eq("recovery_id", goodsRecovery.getId())
                                .eq("delete_flag", 0));
                        if (!list.isEmpty()) {
                            for (GoodsSpecifications goodsSpecification1 : list) {
                                GoodsSpecifications goodsSpecifications = new GoodsSpecifications();
                                goodsSpecifications.setRecoveryId(goodsRecovery1.getId());
                                goodsSpecifications.setDeleteFlag(0);
//                                    // 确保 attributeValue 已经被序列化
//                                    if (goodsSpecifications.getAttributeValueJson() != null) {
//                                        goodsSpecifications.getAttributeValueJson().toString();
//                                        String jsonString = goodsSpecifications.getAttributeValueJson().toString();
//                                        goodsSpecifications.setAttributeValue(jsonString);
//                                    }
                                goodsSpecifications.setAttributeName(goodsSpecification1.getAttributeName());
                                goodsSpecifications.setAttributeValue(goodsSpecification1.getAttributeValue());
                                goodsSpecifications.setAttributes(goodsSpecification1.getAttributes());
                                goodsSpecifications.setTypeStatus(goodsSpecification1.getTypeStatus());
                                goodsSpecifications.setPrice(goodsSpecification1.getPrice());
                                goodsSpecifications.setSpecImg(goodsSpecification1.getSpecImg());
                                goodsSpecifications.setCreateTime(new Date());
                                goodsSpecificationsDao.insert(goodsSpecifications);
                            }
                        }
                    }
                } else {
                    return Result.error("请先添加商品品牌");
                }
            }
        }
        return Result.success("复制成功");
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result copyBrandListByOrdinary(Long labelId, Long brandId) {
        LabelType labelType = labelTypeDao.selectById(labelId);
        Long labelId1;
        LabelType labelType1 = labelTypeDao.selectLabelByOrdinary(labelType.getLabel());
        if (labelType1 == null) {
            LabelType labelType2 = new LabelType();
            labelType2.setLabel(labelType.getLabel());
            labelType2.setIsEnable(1);
            labelType2.setIsRecovery(1);
            labelType2.setIsType(0);
            labelType2.setCreateTime(LocalDateTime.now());
            labelTypeDao.insert(labelType2);
            labelId1 = labelType2.getLabelId();
        } else {
            labelId1 = labelType1.getLabelId();
        }
        List<GoodsRecovery> goodsRecoveryList = goodsRecoveryDao.selectList(new QueryWrapper<GoodsRecovery>().eq("brand_id", brandId));
        if (goodsRecoveryList != null) {
            Brand brand1 = baseMapper.selectById(brandId);
            if (brand1 != null) {
                Brand brand = new Brand();
                brand.setLabelId(labelId1);
                brand.setBrandName(brand1.getBrandName());
                brand.setImg(brand1.getImg());
                brand.setSort(brand1.getSort());
                brand.setCreateTime(new Date());
                brand.setState(brand1.getState());
                brand.setClassify(brand1.getClassify());
                brand.setIsHot(brand1.getIsHot());
                baseMapper.insert(brand);
                for (GoodsRecovery goodsRecovery : goodsRecoveryList) {
                    GoodsRecovery goodsRecovery1 = new GoodsRecovery();
                    goodsRecovery1.setName(goodsRecovery.getName());
                    goodsRecovery1.setBrandId(brand.getId());
                    goodsRecovery1.setCreateTime(new Date());
                    goodsRecovery1.setDeleteFlag(0);
//                            goodsRecovery1.setUpdateBy(userId);
                    goodsRecoveryDao.insert(goodsRecovery1);
                    List<GoodsSpecifications> list = goodsSpecificationsDao.selectList(new QueryWrapper<GoodsSpecifications>()
                            .eq("recovery_id", goodsRecovery.getId())
                            .eq("delete_flag", 0));
                    if (!list.isEmpty()) {
                        for (GoodsSpecifications goodsSpecification1 : list) {
                            GoodsSpecifications goodsSpecifications = new GoodsSpecifications();
                            goodsSpecifications.setRecoveryId(goodsRecovery1.getId());
                            goodsSpecifications.setDeleteFlag(0);
//                                    // 确保 attributeValue 已经被序列化
//                                    if (goodsSpecifications.getAttributeValueJson() != null) {
//                                        goodsSpecifications.getAttributeValueJson().toString();
//                                        String jsonString = goodsSpecifications.getAttributeValueJson().toString();
//                                        goodsSpecifications.setAttributeValue(jsonString);
//                                    }
                            goodsSpecifications.setAttributeName(goodsSpecification1.getAttributeName());
                            goodsSpecifications.setAttributeValue(goodsSpecification1.getAttributeValue());
                            goodsSpecifications.setAttributes(goodsSpecification1.getAttributes());
                            goodsSpecifications.setTypeStatus(goodsSpecification1.getTypeStatus());
                            goodsSpecifications.setPrice(goodsSpecification1.getPrice());
                            goodsSpecifications.setSpecImg(goodsSpecification1.getSpecImg());
                            goodsSpecifications.setCreateTime(new Date());
                            goodsSpecificationsDao.insert(goodsSpecifications);
                        }
                    }
                }
            } else {
                return Result.error("请先添加商品品牌");
            }
        }
        return Result.success("复制成功");
    }
}




